"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 数据库系统
Case Name   : 删除pid文件权限，进行主备切换
Create At   : 2020/07/23
@zou_jialiang0505328126
Description :
    1.修改pid文件权限
    2.主备切换
    3.恢复pid文件权限
    4.主备切换
    5.查询集群状态
    6.进行建表插数据等操作
Expect      :
    1.修改pid文件权限成功
    2.主备切换失败
    3.恢复pid文件权限成功
    4.主备切换成功
    5.查询集群状态成功
    6.进行建表插数据等操作成功
History     :
    2020/07/23 created by @wan005
    2021/05/17 modified by @peilinqian 优化脚本逻辑,以及状态查询适配；
    2021/07/14 modified by @wan005 优化主备状态核对方法；
"""

import os
import time
import unittest

from testcase.utils.Common import Common
from testcase.utils.CommonSH import *
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from yat.test import Node
from yat.test import macro


class ModifyPidFile(unittest.TestCase):
    nodes_tuple = ('PrimaryDbUser', 'Standby1DbUser', 'Standby2DbUser')

    @RestartDbCluster(*nodes_tuple)
    def setUp(self):
        self.log = Logger()
        self.common = Common()

        self.log.info("----this is setup----")
        self.pri_dbuser = Node(node='PrimaryDbUser')
        self.sta1_dbuser = Node(node='Standby1DbUser')
        self.sta1_root = Node(node='Standby1Root')
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.sta_1_sh = CommonSH('Standby1DbUser')
        self.constant = Constant()
        self.postmaster_file = os.path.join(macro.DB_INSTANCE_PATH,
                                            macro.DB_POSTMASTER_PID_NAME)
        self.log.info('----Opengauss_Reliability_Dbsys_Case128.py start----')

    def test_modify_pidfile(self):
        try:
            self.log.info("----1、chmod 000 postmaster.pid ----")
            chmod_cmd = f'chmod 000 {self.postmaster_file};' \
                f'ls -al {self.postmaster_file}'
            tmp = self.sta1_root.sh(chmod_cmd).result()
            self.log.info(tmp)

            self.log.info('----2、执行switchover----')
            result_msg = self.constant.PERMISSION_DENY_MSG
            switchover_result = self.sta_1_sh.executeGsctl('switchover',
                                                           result_msg)
            self.assertTrue(switchover_result)

            self.log.info('----查询主备状态----')
            self.sta_1_sh.getDbClusterStatus('status')

            self.log.info('----3、recover pid ----')
            chmod_cmd = f'chmod 600 {self.postmaster_file};' \
                f'ls -al {self.postmaster_file}'
            tmp = self.sta1_root.sh(chmod_cmd).result()
            self.log.info(tmp)

            time.sleep(5)

            self.log.info('----4、再次进行switchover----')
            success_msg = self.constant.SWITCH_SUCCESS_MSG
            switchover_result = self.sta_1_sh.executeGsctl('switchover',
                                                           success_msg)
            self.assertTrue(switchover_result)
            refreshconf_result = self.sta_1_sh.exec_refresh_conf()
            self.assertTrue(refreshconf_result)

            self.log.info('----5、查询主备状态----')
            db_status = self.sta_1_sh.getDbClusterStatus('detail')
            self.log.info(db_status)
            self.assertIn(self.constant.PRIMARY_NORMAL, db_status)

            self.log.info('----6、主机进行建表等操作----')
            create_sql = 'create table dbsys128(id int); ' \
                         'insert into dbsys128 values' \
                         '(generate_series(1,10000));'
            select_sql = 'select count(*) from dbsys128;'
            sql_result = self.sta_1_sh.executDbSql(create_sql)
            self.log.info(sql_result)
            self.assertIn(self.constant.CREATE_TABLE_SUCCESS, sql_result)
            sql_result = self.sta_1_sh.executDbSql(select_sql)
            self.log.info(sql_result)
            self.assertIn('10000', sql_result)
            sql_result = self.sta_1_sh.executDbSql('drop table dbsys128;')
            self.log.info(sql_result)
            self.assertIn(self.constant.DROP_TABLE_SUCCESS, sql_result)

        finally:
            self.log.info("----recover pid----")
            chmod_cmd = f'chmod 600 {self.postmaster_file};' \
                f'ls -al {self.postmaster_file}'
            tmp = self.sta1_root.sh(chmod_cmd).result()
            self.log.info(tmp)

            self.log.info('----7、switchover，恢复主备关系----')
            success_msg = self.constant.SWITCH_SUCCESS_MSG
            switchover_result = self.pri_sh.executeGsctl('switchover',
                                                         success_msg)
            self.assertTrue(switchover_result)
            refreshconf_result = self.pri_sh.exec_refresh_conf()
            self.assertTrue(refreshconf_result)

            self.log.info('----查询主备状态----')
            status = self.pri_sh.getDbClusterStatus('status')
            self.assertTrue(status)

    def tearDown(self):
        self.log.info("----this is tearDown----")
        self.log.info('----Opengauss_Reliability_Dbsys_Case128.py 执行结束----')
